<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>CITECT 用户管理</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="citect usermanager" />
<meta name="keywords" content="citect datatables usermanager" />
<meta name="author" content="jimmy lee" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

<!--  Bootstrap -->
<link rel="stylesheet" href="<%=basePath%>content/bootstrapV3.0.0/css/bootstrap.min.css" type="text/css" >
<!--font awesome -->
<link rel="stylesheet" href="<%=basePath%>content/font-awesome/css/font-awesome.min.css" type="text/css" >

<!-- ZTree CSS -->
<link rel="stylesheet" href="content/ztree/css/awesomeStyle/awesome.css" type="text/css">

<!--jquery_datatables 样式-->
<link rel="stylesheet" href="<%=basePath%>content/jquery_datatables/css/dataTables.bootstrap.min.css" type="text/css" >
<!--<link rel="stylesheet" href="<%=basePath%>content/jquery_datatables/css/dataTables.jqueryui.min.css" type="text/css" >-->
<!--<link rel="stylesheet" href="<%=basePath%>content/jquery_datatables/row_details/DT_bootstrap.css" type="text/css" >-->

<!--admin lte2 -->
<link rel="stylesheet" href="<%=basePath%>content/adminlte/css/AdminLTE.min.css" type="text/css" >
<!--admin lte2 skin choose -->
<link rel="stylesheet" href="<%=basePath%>content/adminlte/css/skins/_all-skins.min.css" type="text/css" >

 <!--自定义-->
<link rel="stylesheet" href="<%=basePath%>content/common/css/common.css" type="text/css" >

<style type="text/css">
    #dt_example .row:first-child,.dataTables_info{
        color: white;
    }

    #dt_example .row:first-child select option{
        color: black;
    }
    
    .content .row option{
        color: black;
    }
    .row-details:hover{
        cursor:pointer;
    }

</style>

</head>
<body class="skin-blue " oncontextmenu="prevent_rightkeydown();">  
    <div class="wrapper ">
        
    <!-- Content Wrapper. Contains page content -->
    <div class="" style="">
      <!-- Content Header (Page header) -->
      <section class="content-header" style="color:white">
        <h1>
          角色配置
          <small></small>
        </h1>
        
      </section>

      <!-- Main content -->
      <section class="content">
            <div class="row" >
              <div class="" style="margin-top:0px;height:35px;margin-left: 15px;">
                  <div>
                      <div style="width:150px;float:left">
                          <select id="FilterDateOfType" class="form-control"></select>
                      </div>
                      <div style="width:200px;float:left;margin-left:10px" data-column="-1">
                          <input type="text" class="global_filter form-control" placeholder="在结果中搜索" id="jimmylee_filter">
                      </div>
                      <p style="margin-right: 20px;" class="pull-right">
                          <button class="btn  btn-default" id="btn_reflash">刷新</button>
                          <button class="btn  btn-default" id="btn_edit">编辑</button>
                          <button class="btn  btn-default" id="btn_add">增加</button>
                          <button class="btn  btn-default" id="btn_del" onclick="delete_roleinfo();">删除</button>
                      </p>  
                      
                  </div>
              </div>
            </div>
            <div id="dt_example" class="main_datatalbe" style="margin:10px 0 0 0;">
            <table class="table table-condensed table-striped table-hover table-bordered pull-left" id="main_datatalbe" width="100%" cellspacing="0">
            
                <thead></thead>
                <tbody></tbody>
            </table>
                <div class="clearfix"></div>
            </div>
      </section><!-- /.content -->
    </div><!-- /.content-wrapper -->
    </div>
     
    <!-- 用户编辑模态窗口（新增共用）start -->
    <div class="modal" id="userModal" tabindex="-1" role="dialog"
     aria-labelledby="userModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close"
                        data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="userModalLabel">
                    <label class="grouplabel"><i class="fa fa-user"></i> 角色信息</label>
                </h4>
            </div>
            <div class="modal-body">
                <div class="modal_body_content">
                   <form class="form-horizontal no-margin">      
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">角色名</label>
                                    <div class="col-sm-10">
                                        <div class="row">
                                            <div class="col-sm-4">
                                                <input class="form-control" id="input_rolename" placeholder="请输入角色名称">
                                            </div>
                                            <span class="mini-title-input col-sm-1">
                                                
                                            </span>
                                        </div>
                                    </div>
                                </div>                         
                    </form>
                   <form class="form-horizontal no-margin">      
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">权限</label>
                                    
                                    <div class="col-sm-10">
                                        <div class="row">
                                            <div id="modal_rolelist_list" class="col-sm-5">
                                                <ul id="roletree" style="overflow-y:scroll;height:400px;"></ul>
                                            </div>
                                            <span class="mini-title-input col-sm-1">
                                                
                                            </span>
                                        </div>
                                    </div>
                                </div>                         
                    </form>
                    
                    
                </div>
            </div>
            <div class="modal-footer">
                
                <button type="button" class="btn btn-default" id="btn_usermodal_update">提交</button>
                <button type="button" class="btn btn-default" data-dismiss="modal" id="btn_usermodal_hide">关闭</button>
            </div>
        </div>
    </div>
</div>
    <!-- 用户编辑模态窗口（新增共用）end -->

    
<!--jquery lib -->   
<script type="text/javascript" src="<%=basePath%>content/jquery.min.1.11.3.js" charset="UTF-8"></script>
<!-- Bootstrap -->
<script type="text/javascript" src="<%=basePath%>content/bootstrapV3.0.0/js/bootstrap.min.js" charset="UTF-8"></script>
<!-- adminlte 不引用无法进行左侧菜单滑动-->
<script type="text/javascript" src="<%=basePath%>content/adminlte/js/app.min.js" charset="UTF-8"></script>

<!--datatables -->
<script src="<%=basePath%>content/jquery_datatables/js/jquery.dataTables.min.js" type="text/javascript" charset="UTF-8"></script>
<script src="<%=basePath%>content/jquery_datatables/js/dataTables.bootstrap.min.js" type="text/javascript" charset="UTF-8"></script>
<!--<script src="<%=basePath%>content/jquery_datatables/js/dataTables.jqueryui.min.js" type="text/javascript" charset="UTF-8"></script>-->
 <!--行扩展 包-->
<!--<script src="<%=basePath%>content/jquery_datatables/js/DT_bootstrap.js" type="text/javascript" charset="UTF-8"></script>-->

 <!-- ztree JS  -->
<script type="text/javascript" src="content/ztree/js/jquery.ztree.core-3.5.js"></script>
<script type="text/javascript" src="content/ztree/js/jquery.ztree.excheck-3.5.js"></script>

<!--layer-->
<script src="<%=basePath%>content/layer/layer.js" type="text/javascript" charset="UTF-8"></script>

<!--common -->
<script src="<%=basePath%>content/common/js/common.js" type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript">
    //禁用右键
    if (window.Event) document.captureEvents(Event.MOUSEUP); 
    document.oncontextmenu = nocontextmenu;  // for IE5+
    document.onmousedown = norightclick;  //for all others
    //ready start
    var main_datatalbe//页面主查询表
    var main_datatalbe_jsapi//
    $(document).ready(function () {
            //datatable原始按钮隐藏
            $("#searchbtn >.fa-spin").hide();
            
            //datatable初始化
            columnsetting = [
                       { "title": "角色名称", "width": "100px", },
                       { "title": "权限名", "width": "100px", },
                       { "title": "角色名", "width": "100px", },//不可见
                       { "title": "角色ID", "width": "50px", }//不可见
            ];
            NoSortable_list = [1,2,3];
            NoSearchable_list = [1,2,3];
            NoSeeable_list = [2,3];
            
            main_datatalbe_jsapi=datatalbes_init_jsapi('main_datatalbe', NoSortable_list, NoSearchable_list, NoSeeable_list, columnsetting);//不需要行扩展不用用此方法初始化，表格样式丢失
            main_datatalbe=datatalbes_init('main_datatalbe', NoSortable_list, NoSearchable_list, NoSeeable_list, columnsetting);
   
            //查询分类
            temps = '<option value="0">- 全部 -</option>'
                 + '<option value="1">角色名称</option>';
               
            $('#FilterDateOfType').append(temps);
            
            //查询 绑定输入搜索事件
            $('input.global_filter').on('keyup click', function () {
                var a = $(this).parents('div').attr('data-column');
                if (a == -1 || typeof (a) == undefined) { filterGlobal(); }
                else { filterColumn(a) };
            });
            
            //获取用户信息
            get_roleinfo();  
            //刷新权限ztree控件
            reflash_roletree();
    })
   
    
    //点击加减按钮 动态在用户角色下面加载用户权限的信息
    $('.table').on('click', 'tbody td .row-details',
               function() {
                   var nTr = $(this).parents('tr')[0];
                   if (main_datatalbe_jsapi.fnIsOpen(nTr)) //判断是否已打开
                   {
                       /* This row is already open - close it */
                       $(this).addClass("fa-plus-circle").removeClass("fa-minus-circle");
                       main_datatalbe_jsapi.fnClose(nTr);
                   } else {
                       /* Open this row */
                       $(this).addClass("fa-minus-circle").removeClass("fa-plus-circle");
                       //  alert($(this).attr("data_id"));
                       //oTable.fnOpen( nTr,
                       // 调用方法显示详细信息 data_id为自定义属性 存放配置ID
                       fnFormatDetails(nTr, $(this).attr("data_id"));
                   }
    });
    
         
    
    //选中行数据获取
    var selrow_obj;//选中行的数据对象    
    //表格选中 针对datatable实例初始化
    $('#main_datatalbe tbody').on( 'click', 'tr[role="row"]', function () {
        selrow_obj=main_datatalbe.row( this ).data();
        //
        main_datatalbe.$('tr.selected').removeClass('selected');
        $(this).toggleClass('selected');
    } );
    
    //角色点击事件触发 权限详细信息加载 urid 角色的urid
    fnFormatDetails=function(nTr, urid) { 
        
        var roleinfo = roleinfo_obj
        var sOut = '<table style="width:100%;">';
        for(var i=0;i<roleinfo.length;i++){
            if(roleinfo[i].urid==urid){
                obj_t=roleinfo[i].privileges;
                
                $.each(obj_t, function (idx, item) {
                    sOut+='<tr>';
                    sOut+='<td width="50%"></td>';
                    sOut+='<td width="50%">'+item.privilegeName+'</td>';
                    sOut+='</tr>'
                });
                
            }
        }
        sOut+='</table>';
        main_datatalbe_jsapi.fnOpen( nTr,sOut, 'details' ); 
}

    
    //获取角色信息 绑定到用户信息表
    var roleinfo_obj;//刷新表格的时候获取用户角色信息
    get_roleinfo=function(){
         //获取所有用户信息 不分页
         SendAjax("${basePath}userRole/getUserRoleByParams", null, false,
                function (datastr) {
                    if (datastr) {
                        //var result = eval("(" + datastr + ")");
                        result=datastr.rows;
                        roleinfo_obj=datastr.rows;
                        if (result && result.length > 0) {
                            var contentlist = [];//保存data内容
                            
                            //有数据进行处理
                            for (var i = 0; i < result.length; i++) {
                                //
                                var obj = result[i];
                                contentlist.push([
                                  "<i class='row-details fa fa-plus-circle' data_id='" + obj.urid + "'></i>&nbsp;"+obj.roleName,
                                  "<i class='fa fa-suitcase'></i>",
                                  obj.roleName,
                                  obj.urid,
                                ]);                                 
                            }
                            //如果有数据 刷新datatables控件
                            if (contentlist.length >= 1) {
                                main_datatalbe.rows.add(contentlist).draw();
                            }      
                        }
                        else {
                            $("#main_datatalbe.dataTables_empty").show();
                        }
                    }
                },
                { 'errormsg': '查询信息失败', 'errorfunction': null },
                { 'timeoutmsg': '查询信息超时', 'timeoutset': -1, 'timeoutfunction': null });
    }
    
    //权限树刷新
    var zNodes = [];
    reflash_roletree=function(){
        var ul = document.getElementById("roletree");
        var priArr = get_priinfo();
        for (var i = 0; i < priArr.length; i++) {
            var dp = priArr[i];
            open_t = true;

            var node = { id: dp.upid, pId: "", name: dp.privilegeName, open: open_t, isParent: true };
            zNodes.push(node);
        }

        if (!ul.classList.contains("ztree"))
            ul.classList.add("ztree");

        var setting = {
            check: {
                enable: true,
                chkStyle: 'checkbox',
                radioType: "level",
                type: { "Y": "s", "N": "s" }
            },
            view: {
                fontCss: function (treeId, node) {
                    return node.isParent ? { "font-size": "18px" } : { "font-size": "18px" };
                },
                showLine: false,
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {//回调绑定
                onClick: function (e, treeId, treeNode) {
                    var zTreeobj = $.fn.zTree.getZTreeObj(treeId);
                    zTreeobj.checkNode(treeNode, !(treeNode.checked), true);//点击的对象都变为checked
                    //展开树
                    //zTreeobj.expandNode(treeNode, !(treeNode.open), false, false);
                }
            },
        
        };

        $.fn.zTree.init($(ul), setting, zNodes);
    }
    
    
    //获取权限信息 刷新ztree
    var get_priinfo=function(){
        var result;
        //获取所有用户信息 不分页
        SendAjax("${basePath}userPrivilege/getUserPrivilegeByParams", null, false,
               function (datastr) {
                   if (datastr) {
                       result=datastr.rows;
                       
                   }
                   else{
                       result= null;
                   }
               },
               { 'errormsg': '查询信息失败', 'errorfunction': null },
               { 'timeoutmsg': '查询信息超时', 'timeoutset': -1, 'timeoutfunction': null });
        return result;//返回值 不能放在回调里面
    }
    
    
    //增加角色
    add_rolenfo=function(){
        var jsonobj = check_info();
        if(!jsonobj)return null;//用户信息校验未通过，退出
         SendAjax("${basePath}userRole/addUserRole", jsonobj, false,
                function (datastr) {
                    if (datastr) {
                        var code_t=datastr.code;
                        var message_t=datastr.message;
                        alert(message_t);
                        if(code_t="success"){   
                            //操作成功，关闭窗口
                            hide_usermodal();
                            document.getElementById("btn_reflash").click(); 
                        }
                        else if(code_t="error"){
                            //nothing
                        }
                        else{
                            //nothing
                        }
                    }
                   
                },
                { 'errormsg': '新增操作失败', 'errorfunction': null },
                { 'timeoutmsg': '新增操作超时', 'timeoutset': -1, 'timeoutfunction': null });
    }
    //更新用户 必要参数 uid/userName/password/stationName/urid
    update_priinfo=function(){
        var jsonobj = check_info();
        if(!jsonobj)return null;//用户信息校验未通过，退出
        //获取所有用户信息 不分页
         SendAjax("${basePath}userRole/updateUserRole", jsonobj, true,
                function (datastr) {
                    if (datastr) {
                        var code_t=datastr.code;
                        var message_t=datastr.message;
                        alert(message_t)
                        if(code_t="success"){   
                            //操作成功，关闭窗口 
                            hide_usermodal();
                            document.getElementById("btn_reflash").click(); 
                        }
                        else if(code_t="error"){
                            //nothing
                        }
                        else{
                            //nothing
                        }

                    }
                },
                { 'errormsg': '更新操作失败', 'errorfunction': null },
                { 'timeoutmsg': '更新操作超时', 'timeoutset': -1, 'timeoutfunction': null });
    }
    //删除用户 必要参数 uid
    delete_roleinfo=function(){
        //获取选中行的uid
        if(!selrow_obj){
            alert("没有用户数据被选中。");
            return null;
        }
        var urid_t=selrow_obj[3];
        var jsonobj = { urid : urid_t };
        SendAjax("${basePath}userRole/deleteUserRole", jsonobj, false,
               function (datastr) {
                   if (datastr) {
                       var code_t=datastr.code;
                       var message_t=datastr.message;
                       alert(message_t)
                       if(code_t="success"){   
                           
                           document.getElementById("btn_reflash").click(); 
                       }
                       else if(code_t="error"){
                           
                           //nothing
                       }
                       else{
                           //nothing
                       }
                   }
               },
               { 'errormsg': '删除操作失败', 'errorfunction': null },
               { 'timeoutmsg': '删除操作超时', 'timeoutset': -1, 'timeoutfunction': null });
    }
    
    hide_usermodal=function(){
        $('#userModal').modal('toggle');
        //document.getElementById("userModal").modal('toggle');
    }
    //信息数据校验
    var check_info=function(){
        var rolename_t=document.getElementById('input_rolename').value;  

        if(rolename_t==""){
            alert("请填写角色名称");
            return null;
        }
        
        var priid_t=getTreeCheck("roletree");//权限数组获取
        if(!priid_t){
            alert("请勾选权限");
            return null;
        }
        
        //privileges 传入的是权限ID 不是权限的编号
        var jsonobj = { roleName: rolename_t , upid : priid_t };
        if(operflag==0){ //更新操作 需要补充uid
            jsonobj.urid=  selrow_obj[3].toString();
        }
        return jsonobj;
    }
    //获取角色树上选择的对象数组
    var getTreeCheck=function(ulid) {
        var zTree = $.fn.zTree.getZTreeObj(ulid);
        var arrCheckNode = zTree.getCheckedNodes(true);
        if (arrCheckNode == null || arrCheckNode.length == 0)
            return null;
        var privileges = new Array();
        for (var i = 0; i < arrCheckNode.length; i++) {
            var node = arrCheckNode[i];
            privileges.push((node.id).toString());
        }
        return privileges;
    }
   
    
    //刷新用户信息表
    $('#btn_reflash').on('click','' , function () {
        main_datatalbe.clear();
        get_roleinfo();
    })
    
    var operflag;//窗口操作标志 0 更新/1新增
    //绑定table点击事件，弹出模态框             
    $('#btn_edit').on('click','' , function () {
        //获取选中行的uid
        if(!selrow_obj){
            alert("没有角色被选中。");
            return null;
        }
        user_modal_clean();
        //窗口操作类型
        operflag=0;
        //初始化窗口信息
        initial_edit_modal(selrow_obj);
        show_eidt_modal(this);
        //刷新modal的窗体信息
    });
    
    //初始化编辑窗口 用选择的列对象
    initial_edit_modal=function(selrowobj){
        //初始化角色名称
        document.getElementById('input_rolename').value=selrowobj[2];
        //初始化权限树
        var treeObj = $.fn.zTree.getZTreeObj("roletree");
        var roleinfo = roleinfo_obj 
        for(var i=0;i<roleinfo.length;i++){
            if(roleinfo[i].urid==selrowobj[3]){
                obj_t=roleinfo[i].privileges;
                for (var i1 = 0; i1 < obj_t.length; i1++) {
                    $.each(treeObj.getNodes(), function (idx, item) {  
                        if(item.id==obj_t[i1].upid)treeObj.checkNode(item, true, true);;   
                    });
                }
            }   
        }
    }
    //新增角色
    $('#btn_add').on('click','' , function () {
        //
        user_modal_clean();
        //窗口操作类型
        operflag=1;
        show_eidt_modal(this);

    })

    
    $('#btn_usermodal_update').on('click','' , function () {
        if(operflag==1){//新增
            add_rolenfo();
        }
        else if(operflag==0){//更新
            update_priinfo();
        }
        else{
            //nothing
        }
        

    })
        
    
    //清空模态窗口内容
    user_modal_clean=function(){
        //角色的名称清空
        document.getElementById('input_rolename').value='';
        //权限树的选择清空
        var treeObj = $.fn.zTree.getZTreeObj("roletree");
        treeObj.checkAllNodes(false);
        
    }
    
    
    
    //弹出用户编辑窗口
    show_eidt_modal=function(){
        $('#userModal').modal('show');
    }
    
    //自定义搜索过滤 jquery datatables控件
    function filterGlobal() {
        $('#main_datatalbe').DataTable().search(
            $('#jimmylee_filter').val(),
            true,
            true
        ).draw();
    }

    function filterColumn(i) {
        $('#main_datatalbe').DataTable().column(i).search(
            $('#jimmylee_filter').val(),
            true,
            true
        ).draw();
    }

    //过滤列的选择
    $('#FilterDateOfType').on('click', 'option', function () {
        var a = parseInt($(this).attr('value'));
        $('input.global_filter').parents('div').attr('data-column', a - 1);
    })
    


</script>
</body>
</html>